/*
 * Copyright 2004-2024 H2 Group. Multiple-Licensed under the MPL 2.0,
 * and the EPL 1.0 (https://h2database.com/html/license.html).
 * Initial Developer: H2 Group
 */
package org.h2.expression.function.table;

import org.h2.api.ErrorCode;
import org.h2.engine.SessionLocal;
import org.h2.expression.Expression;
import org.h2.expression.function.CSVWriteFunction;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.schema.FunctionAlias.JavaMethod;
import org.h2.tools.Csv;
import org.h2.tools.FileTool;
import org.h2.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * A 从pip里面读取内容 function.
 */
public final class FileReadFunction extends TableFunction {

    public FileReadFunction() {
        super(new Expression[4]);
    }

    FileTool csv = new FileTool();

    @Override
    public ResultInterface getValue(SessionLocal session) {
        session.getUser().checkAdmin();
        //FileTool csv = new FileTool();
        try {
            // TODO create result directly
            //System.out.println("[bzm]getValue");
            ResultSet resultSet = csv.read(args, session, "utf-8");
            //System.out.println("[bzm]getValue->columnNames4=" + resultSet.getMetaData().getColumnCount());
            return JavaMethod.resultSetToResult(session, resultSet, Integer.MAX_VALUE);
        } catch (Exception e) {
            throw DbException.convert(e);
        }
    }


    @Override
    public void optimize(SessionLocal session) {
        super.optimize(session);
        int len = args.length;
        if (len < 1 || len > 7) {
            throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, getName(), "1..7");
        }
    }

    @Override
    public ResultInterface getValueTemplate(SessionLocal session) {
        session.getUser().checkAdmin();
        ResultInterface result;
        //System.out.println("[bzm]getValueTemplate");
        try (ResultSet rs = csv.read(args, session, "utf-8")) {
            result = JavaMethod.resultSetToResult(session, rs, 0);
        } catch (SQLException e) {
            throw DbException.convert(e);
        }
        return result;
    }


    @Override
    public String getName() {
        return "FILEREAD";
    }

    @Override
    public boolean isDeterministic() {
        return false;
    }

}
